package custom;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;


/**
 * @author:Eric
 * @date:2021/8/4 10:24
 * 自定义消息的服务端
 */
@Slf4j
public class CustomServer {

    public void start(int port) throws Exception {

        //监听连接
        NioEventLoopGroup boos = new NioEventLoopGroup();
        //处理IO事件
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boos, worker)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    //自定义解码器
                                    .addLast(new CustomDecoder())
                                    //字符串编码器
                                    .addLast(new StringEncoder())
                                    //自定义服务端处理器
                                    .addLast(new ServerHandler());
                        }
                    });
            //启动服务端
            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("服务端启动成功,port：{}", port);
            //对关闭通道进行监听
            future.channel().closeFuture().sync();
        } finally {
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }

    public static void main(String[] args) throws Exception {
        new CustomServer().start(8989);
    }
}
